$(document).ready(function () {
    //页面加载，请求书签数据
    let booklist = []
    $.post('../selectbook.php',res=>{
        if(res){
            booklist = JSON.parse(res)
        }
        $(".btnbox button:first").children('a').click()
    })

    //隐藏对话框——取消按钮
    $(".dialogbox .cancel").click(function(){
        $(".dialogbox").hide()
    })
    //弹出对话框——修改昵称按钮
    $("#reuser").click(function(){
        $(".dialog").hide()
        $(".reuser-dialog").show()
        $(".dialogbox").show()

        //在弹出框里显示当前昵称
        $("#toreuser").siblings('p').children('input').val($("#petname").html())
    })
    //弹出对话框——新增收藏夹按钮
    $("#addcata").click(function(){
        $.get('../judgelogin.php',res=>{
            if(res){
                alert("未登录，请登录后操作")
                location = "../login.html"
            }
        }) //判断是否登录，未登录则跳转到登录页

        $(".dialog").hide()
        $(".cata-dialog").show()
        $(".dialogbox").show()
    })
    //弹出对话框——新增书签按钮
    $("#addbook").click(function(){
        $.get('../judgelogin.php',res=>{
            if(res){
                alert("未登录，请登录后操作")
                location = "../login.html"
            }
        }) //判断是否登录，未登录则跳转到登录页
        $(".book-dialog p input").val("")
        $(".dialog").hide()
        $(".book-dialog").show()
        $(".dialogbox").show()
    })

    let curbookarr = []  //当前目录下的书签列表

    //目录按钮盒子：修改/删除/目录名
    $(".btnbox").click(function(e){
        
        let cataid = $(e.target).parent().attr("flag")
        
        //弹出对话框——修改按钮
        if(e.target.className == "recatabtn"){
            $(".dialog").hide()
            $(".recata-dialog").show()
            $(".dialogbox").show()

            let cataname = $(e.target).siblings('a').html()
            $("#recata_id").val(cataid)
            $(".recata-dialog p input").val(cataname)
        }

        //目录删除ajax请求——删除按钮
        if(e.target.className == "delcatabtn"){
            if(confirm("是否删除收藏夹以及该收藏夹下的书签")){
                $.get("../delcata.php?cata_id="+cataid)
                //异步处理，删除数据库的同时，在页面删除对应节点
                $(e.target).parent().remove()
                $(".btnbox button:first").children('a').click()
            }
        }


        //点击目录名——渲染相应的书签
        if($(e.target)[0].tagName == "A"){
            //给该button添加点击样式
            $(e.target).parent().css({'backgroundColor':'#0ff'})
            $(e.target).css({'color':'#666'})
            $(e.target).parent().hover(function(){
                $(this).css({'backgroundImage':'url(../images/lt.png)'})
            },function(){
                $(this).css({'backgroundImage':'none'})
            })
            //去除其他button的点击样式
            $(e.target).parent().siblings('button').css({'backgroundColor':'#fff'})
            $(e.target).siblings('button').css({'color':'#000'})
            $(e.target).parent().siblings('button').hover(function(){
                $(this).css({'backgroundImage':'url(../images/increase.png)'})
            },function(){
                $(this).css({'backgroundImage':'none'})
            })

            //渲染相应的书签
            $(".bookmarks ul").empty() //清空现有书签
            $(".bookmarks ul").attr('flag',cataid)
            curbookarr = []
            for(let i in booklist){
                if(booklist[i].bookcata === cataid){
                    curbookarr.push(booklist[i])
                }
            }
            let pagecount = Math.ceil(curbookarr.length/15)
            pagecount = pagecount == 0 ? 1 : pagecount
            $("#page").empty() //清空当前页码
            for(let i = 0 ; i < pagecount ; i++){
                let el_a = ` <a href="#">${i+1}</a> `
                $("#page").append(el_a)
            }

            $("#page a:first").click()

        }

    })

    //新增目录ajax请求
    $("#toaddcata").click(function (e) {
        if(inpLimit($(this)) == false){
            return false
        }
        
        let newcata = $(this).siblings('p').children('input').val()
        $.post('../addcata.php',{newcata:newcata},res=>{
            $(".btnbox button:last").attr("flag",res)
        })
        let el = document.createElement('button')
        let children = `
            <a href="#"></a>
            <img src="./images/alter.png" alt="" class="recatabtn">
            <img src="./images/del.png" alt="" class="delcatabtn">`
        $(el).append(children)
        $(el).children('a').text(newcata)
        $(".btnbox").append(el)

        $(".dialogbox").hide()
        return false
    })

    //修改目录ajax请求
    $("#torecata").click(function(e){
        if(inpLimit($(this)) == false){
            return false
        }
        let cataid = $("#recata_id").val()
        let cataname = $(this).siblings('p').children('input').val()

        $.post('../recata.php',{recata_id:cataid,recata:cataname})
        
        $("button[flag="+cataid+"]>a").html(cataname)
        $(".dialogbox").hide()
        return false
    })

    //修改用户昵称ajax
    $("#toreuser").click(function(){
        if(inpLimit($(this)) == false){
            return false
        }
        
        let petname = $(this).siblings('p').children('input').val()
        $.post('../reuser.php',{petname:petname})
        
        $("#petname").text(petname)
        $(".dialogbox").hide()
        return false
    })

    

    //添加书签ajax
    $("#toaddbook").click(function(){
        if(inpLimit($(this)) == false){
            return false
        }
        
        //格式化网址
        let url = $(this).siblings('p').children('input').val() //输入的网址
        //如果 有http，没有www
        if(url.match(/^http/i) != null && url.match(/^https?\:\/\/www/i) == null){
            if(url.match(/^https/i) != null){ //有https
                url = url.replace(/^https:\/\//i,'https://www.')
            }else{
                url = url.replace(/^http:\/\//i,'http://www.')
            }
        }else if(url.match(/^www/i) != null){   //如果 没有http，有www
            url = 'http://' + url
        }else if(url.match(/^http/i) == null && url.match(/^https?\:\/\/www/i) == null){
            url = 'http://www.' + url
        }

        //根据网址获取网站图标网址
        let iconUrl = url + '/'
        iconUrl = iconUrl.match(/^https?\:\/\/[^\/]+\//) + 'favicon.ico'

        //添加书签ajax
        let bookcata = $(".bookmarks ul").attr('flag') //获取目录id
        $.post('../addbook.php',{bookurl:url,bookicon:iconUrl,bookcata:bookcata},res=>{
            if(res){
                let bookarr = JSON.parse(res)
                $(".bookmarks ul li:last").attr('flag',bookarr['bookid'])
                $(".bookmarks ul li:last").children('span').text(bookarr['bookname'])
                let newbook = {
                    bookid:bookarr['bookid'],
                    bookicon:iconUrl,
                    bookname:bookarr['bookname'],
                    bookurl:url,
                    bookcata:bookcata
                }
                booklist.push(newbook)
                curbookarr.push(newbook)
                let pagecount = Math.ceil(curbookarr.length/15)
                $("#page").empty() //清空当前页码
                for(let i = 0 ; i < pagecount ; i++){
                    let el_a = ` <a href="#">${i+1}</a> `
                    $("#page").append(el_a)
                }
                $("#page a:last").click()
            }
        })
        
        let li_length = $(".bookmarks ul li").length
        if(li_length <= 14){
            let bookli = document.createElement('li')
            bookli.setAttribute('flag', '')
            bookli.innerHTML = `
                <img src="${iconUrl}" alt="">
                <span></span>
                <a href="${url}" target="_blank"></a>
                <div class="del delbtn">
                    <img src="./images/del.png" alt="">
                </div>`
            $(bookli).children('span').text(url)
            $(bookli).children('a').text(url)
            $(".bookmarks ul").append(bookli)
        }
        
        $(".dialogbox").hide()
        return false
    })

    //删除书签ajax
    $(".bookmarks ul").click(function(e){
        if($(e.target).parent().attr('class') == 'del'){
            if(confirm("是否删除此书签？")){
                let bookid = $(e.target).parents('li').attr('flag')
                $.get('../delbook.php?bookid='+bookid)
                $(e.target).parents('li').remove()
                for(let i in curbookarr){
                    if(curbookarr[i].bookid == bookid){
                        curbookarr.splice(i,1)
                        break
                    }
                }
                $("#page a.flag").click()
            }
        }
    })


    //对弹窗里的input内容做限制
    function inpLimit(el){
        if(el.siblings('p').children('input').val() == ""){
            alert("不能为空")
            return false
        }
        if(el.siblings('p').children('input').val().length > 256){
            alert("输入过长")
            return false
        }
    }

    //分页功能
    $("#page").click(function(e){
        if(e.target.tagName == 'A'){
            //修改页码样式
            $("#page").children('a').css({'color':'#ccc','fontWeight':'normal'})
            $(e.target).css({'color':'#14b6f6','fontWeight':'bold'})
            $(e.target).siblings('a').removeClass()
            $(e.target).attr('class','flag')

            let page = parseInt(e.target.innerHTML)
            let curpagebookarr = []
            if(curbookarr[(page-1)*15]){
                curpagebookarr = curbookarr.slice((page-1)*15,page*15)
            }else{
                $("#page a:last").remove()
                $("#page a:last").click()
                return
            }
            $(".bookmarks ul").empty() //清空现有书签
            let frag = document.createDocumentFragment()
            for(let i in curpagebookarr){
                let li = document.createElement("li")
                li.setAttribute("flag",curpagebookarr[i].bookid)
                li.innerHTML = `
                    <img src="${curpagebookarr[i].bookicon}" alt="">
                    <span></span>
                    <a href="${curpagebookarr[i].bookurl}" target="_blank"></a>
                    <div class="del" id="delbook">
                        <img src="./images/del.png" alt="">
                    </div>
                    `
                $(li).children('span').text(curpagebookarr[i].bookname)
                $(li).children('a').text(curpagebookarr[i].bookurl)
                frag.appendChild(li)
            }
            $(".bookmarks ul").append(frag)
            frag = null
        }
    })
    //首页
    $("#homepage").click(function(){
        $("#page a:first").click()
    })
    //尾页
    $("#lastpage").click(function(){
        $("#page a:last").click()
    })
    //上一页
    $("#prepage").click(function(){
        if($("#page a.flag").html() > 1){
            $("#page a.flag").prev().click()
        }
    })
    //下一页
    $("#nextpage").click(function(){
        if($("#page a.flag").html() < $("#page a").length){
            $("#page a.flag").next().click()
        }
    })


    //点击colorbar获取颜色值，设置背景色
    $(".colorbar span").click(function(e){
        let color = $(e.target).css("background-color")
        digitarr = color.match(/\d+/g)
        $(".nav").css("background-color","rgba("+digitarr[0]+","+digitarr[1]+","+digitarr[2]+",0.3)")
        $(".bookmarks").css("background-color","rgba("+digitarr[0]+","+digitarr[1]+","+digitarr[2]+",0.4)")
        $(".catalogue").css("background-color","rgba("+digitarr[0]+","+digitarr[1]+","+digitarr[2]+",0.4)")
        $(".footer").css("background-color","rgba("+digitarr[0]+","+digitarr[1]+","+digitarr[2]+",0.5)")
    })

    
    //搜索功能
    $("#searbtn").click(function(){
        let keyword = $("#searword").val()
        $("#searword").val("")
        curbookarr = []
        for(let i in booklist){
            if(booklist[i].bookname.indexOf(keyword) != -1){
                curbookarr.push(booklist[i])
            }
        }
        let pagecount = Math.ceil(curbookarr.length/15)
        pagecount = pagecount == 0 ? 1 : pagecount
        $("#page").empty() //清空当前页码
        for(let i = 0 ; i < pagecount ; i++){
            let el_a = ` <a href="#">${i+1}</a> `
            $("#page").append(el_a)
        }
        $("#page a:first").click()
        return false
    })


    /**
     * 处理底部元素位置
     */
    //函数节流
    function orificing(fn){
        let flag = true
        return function (){
            if(flag){
                fn()
                flag = false
                setTimeout(()=>{
                    flag = true
                }, 100)
            } 
        }
    }
    let fn = orificing(function(){
        if($('.content')[0].offsetTop+$('.content').height() >= window.innerHeight-80){
            $('.footer').removeClass('fixed')
        }else{
            $('.footer').addClass('fixed')
        }
    })
    fn()
    //footer自适应
    window.onresize = fn

    var targetNode = $('.catalogue')[0]//content监听的元素id
    //options：监听的属性
    var options = { attributes: true, childList: true,subtree:true,attributeOldValue:true}
    //回调事件
    function callback(mutationsList, observer) {
        fn()
    }
    var mutationObserver = new MutationObserver(callback)
    mutationObserver.observe(targetNode, options)
})